package com.zpark.hystrix.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zpark.hystrix.feign.IUserServerFeign;
import com.zpark.hystrix.pojo.Ranking;
import com.zpark.hystrix.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.zpark.hystrix.controller
 * @ClassName: Hystrix01Controller
 * @Description:
 * @author: RZS
 * @date: 2022/11/29  10:54
 */
@RestController
@RequestMapping("/hystrix-01")
@DefaultProperties(defaultFallback = "defaultFallback")
public class Hystrix01Controller {

    @Autowired
    private IUserServerFeign userServerFeign;


//    @PostMapping("/all.do")
//    // @HystrixCommand(fallbackMethod = "allFallback")
//    @HystrixCommand
//    public List<Ranking> all(){
//        return userServerFeign.findAll();
//    }

    @PostMapping("/all.do")
    // @HystrixCommand(fallbackMethod = "allFallback")
    @HystrixCommand
    public JsonResult all(){
        return new JsonResult<List<Ranking>>(
                200,
                null,
                userServerFeign.findAll()
        );
    }

//    @GetMapping("/find/{id}")
//    // @HystrixCommand(fallbackMethod = "findFallback")
//    @HystrixCommand
//    public Ranking find(@PathVariable Integer id){
//        return userServerFeign.findById(id);
//    }

    @GetMapping("/find/{id}")
    // @HystrixCommand(fallbackMethod = "findFallback")
    @HystrixCommand
    public JsonResult find(@PathVariable Integer id){
        return new JsonResult<Ranking>(
                200,
                null,
                userServerFeign.findById(id)
        );
    }

    private List<Ranking> allFallback(){
        Ranking r = new Ranking();
        r.setFilmName("当前服务繁忙，请稍后再试.....");
        List<Ranking> list = new ArrayList<>();
        list.add(r);
        return list;
    }

    /**
     * 	要注意；因为熔断的降级逻辑方法必须跟正常逻辑方法保证：相同的参数列表和返回值声明。
     * @param id
     * @return
     */
    // 熔断降级方法
    private Ranking findFallback(@PathVariable Integer id){
        Ranking r = new Ranking();
        r.setFilmName("当前服务繁忙，请稍后再试.....");
        return r;
    }

    // 默认服务降级方法
    private JsonResult defaultFallback(){
        return new JsonResult(
                500,
                "服务器繁忙，稍后再试....JSON_RESULT",
                null
        );
    }
}
